package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.utils.EmailUntil;
import com.ny.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/password")
public class PasswordResetController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private EmailUntil emailUntil;
    
    // 存储验证码的临时存储（实际项目中应使用Redis等缓存）
    private Map<String, String> verificationCodes = new ConcurrentHashMap<>();
    
    // 发送验证码
    @PostMapping("/send-code")
    public Result sendVerificationCode(@RequestParam String email) {
        // 检查邮箱是否存在
        User user = userService.findUserByEmail(email);
        if (user == null) {
            return Result.error("该邮箱未注册");
        }
        
        // 生成验证码
        String code = EmailUntil.generateVerificationCode();
        
        // 保存验证码（实际项目中应设置过期时间）
        verificationCodes.put(email, code);
        
        // 发送邮件
        emailUntil.sendVerificationCode(email, code);
        
        return Result.success("验证码已发送至您的邮箱");
    }
    
    // 验证验证码并重置密码
    @PostMapping("/reset")
    public Result resetPassword(@RequestParam String email, 
                               @RequestParam String code, 
                               @RequestParam String newPassword) {
        // 检查邮箱是否存在
        User user = userService.findUserByEmail(email);
        if (user == null) {
            return Result.error("该邮箱未注册");
        }
        
        // 验证验证码
        String storedCode = verificationCodes.get(email);
        if (storedCode == null || !storedCode.equals(code)) {
            return Result.error("验证码错误或已过期");
        }
        
        // 更新密码
        int result = userService.updatePassword(user.getUser_id(), newPassword);
        if (result > 0) {
            // 清除验证码
            verificationCodes.remove(email);
            return Result.success("密码重置成功");
        } else {
            return Result.error("密码重置失败");
        }
    }
}